import Controller from '../../decorators/controller'
import get from '../../decorators/get'
import post from '../../decorators/post'
import put from '../../decorators/put'
import BaseController from '../base'
import CategoriesDao from '../../dao/categoriesDao'

@Controller('/api/admin/categories')
export default class extends BaseController {
    @get("/")
    list() {
        var params = this.getParams()
        // this.ctx.body = "hello world"
        return CategoriesDao.where(params).page({
            from: params.from,
            limit: params.size
        }).select()
    }

    @get("/count")
    count() {
        var params = this.getParams()
        // this.ctx.body = "hello world"
        return CategoriesDao.where(params).count()
    }

    @get("/select")
    async select() {
        return await CategoriesDao.where({}).select()
    }

    @post("/")
    async add() {
        var payload = this.getBody()
        if (!payload.parentId) {
            delete payload.parentId
        }
        var currentUser = await this.getCurrentUser()
        return await CategoriesDao.add({
            clientId: currentUser.clientId,
            ...payload
        })
    }

    @get("/detail")
    async one() {
        var {id} = this.getParams()
        var results = await CategoriesDao.selectBySql(`
select "ca1".* , "ca2"."name" as "parentName"  from "categories" "ca1"
left join "categories" "ca2" on "ca2"."id"="ca1"."parentId"
where "ca1"."id"=${id}`)
        return results[0]
    }

    @put("")
    async put() {
        var {id} = this.getParams()
        var body = this.getBody()
        var results = await CategoriesDao.update(id, body)
        return results
    }

}


